package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.CircleImageView;
import com.shwread.android.ui.widget.CommentView;
import com.shwread.android.ui.widget.ListenSoftInputMethodLinearLayout;
import com.shwread.android.ui.widget.ListenSoftInputMethodLinearLayout.OnSoftInputMethodListener;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.android.ui.widget.xlistview.XListView;
import com.shwread.android.ui.widget.xlistview.XListView.IXListViewListener;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.face.QryCommentListAction;

import java.util.ArrayList;
import java.util.List;

import logic.bean.CommentBean;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.DateUtil;
import logic.util.ImageLoaderUtil;
import logic.util.NetworkUtil;
import logic.util.Util;


/**
 * @Project： Shwread
 * @Title：CommentListActivity
 * @Description：评论列表
 * @Author：zhangnannan
 * @Date：2015年2月3日
 */
public class CommentListActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener,
        IXListViewListener
{
	private BaseBusinessActivity          bActivity;
	private Context                       context;
	private TextView                      tvTitle;
	private Button                        butBack;
	private XListView                     xListView;
//	private LinearLayout                  llayCommentList;
	private CommentView                   commentView;
//	private View 						  contentView;
	
	private CommentListAdapter            commentListAdapter;
	
	private List<CommentBean>             resultInfo;                                                          //临时存放从服务器取回的数据
	private List<CommentBean>             commentList;                                                         //显示数据用的List
	                                                                                                            
	private String                        targetType;                                                          //评论的内容类型       
	private String                        targetValue;                                                         //评论的内容值
	private long                          currentCommentTime = 0L;                                             //最后一条记录的评论时间戳,首次为零
	private int                           pageNumber         = 20;                                              //每页显示记录数
	private long                          refrushTime;                                                         // 刷新时间
	
	private ListenSoftInputMethodLinearLayout  root_view;
	private boolean                       inputMethodIsShow = false;
	private boolean                       isCommented = false;
	
	private LoadingView loadingView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.comment_list);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		bActivity = this;
		context = this;
		resultInfo = new ArrayList<CommentBean>();
		commentList = new ArrayList<CommentBean>();
		commentListAdapter = new CommentListAdapter();
		Bundle bundle = getIntent().getExtras();
		if (bundle != null)
		{
			targetType = bundle.getString(DefaultConsts.COMMENT_TARGET_TYPE);
			targetValue = bundle.getString(DefaultConsts.COMMENT_TARGET_VALUE);
		}
		else
		{
			finish();
			return;
		}
		
		findView();
		initLoadingView();
		addListener();
		
		getData(0);
	}
	@Override
	protected void onStop() {
	    super.onStop();
	    if(null!=commentView) commentView.hideInputMethod();
	}
	
	private void initLoadingView(){
		loadingView = (LoadingView) findViewById(R.id.comment_list_loading_view);
		loadingView.setDefaultConfig();
		loadingView.setEmptyClickListener(new ViewClick());
		loadingView.setFailClickListener(new ViewClick());
		loadingView.changeLoadingStatus(0);
		loadingView.setVisibility(View.VISIBLE);
		xListView.setVisibility(View.GONE);
//		contentView.setVisibility(View.GONE);
	}
	private class ViewClick implements OnClickListener{
		@Override
        public void onClick(View v) {
			loadingView.changeLoadingStatus(0);
			loadingView.setVisibility(View.VISIBLE);
			xListView.setVisibility(View.GONE);
			getData(0);
        }
	}
	
	@SuppressLint ("HandlerLeak")
    private Handler handler = new Handler()
	                        {
		                        @Override
		                        public void handleMessage(Message msg) {
			                        switch (msg.what) {
										case DefaultConsts.COMMENT_LIST_UPDATEUI:
											setData(msg);
											break;
										case DefaultConsts.COMMENT_SUBMIT_SUCCESS:
											isCommented = true;
											getData(-1);
//											Util.showToast(context, "评论成功");
											break;
										case DefaultConsts.COMMENT_SUBMIT_ERROR:
//											Util.showToast(context, "评论失败");
											break;
									}
								}
	                        };
	
	@Override
	public Handler getUIHandler() {
		return handler;
	}
	
	private void findView() {
		root_view =(ListenSoftInputMethodLinearLayout)findViewById(R.id.root_view);
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		butBack = (Button) findViewById(R.id.common_header_back);
		tvTitle.setText(getResources().getString(R.string.comment_title_text));//评论
		butBack.setVisibility(View.VISIBLE);
		
		xListView = (XListView) findViewById(R.id.comment_list_lv);
		
		commentView = (CommentView) findViewById(R.id.comment_list_comment_view);
		
		root_view.setOnSoftInputMethodListener( new OnSoftInputMethodListener ( ) {
			@Override
			public void OnSoftInputMethodChanged(boolean isShow){
				inputMethodIsShow = isShow;
			}
		});
	}
	
    private boolean resetCommentView( ) {
    	if(inputMethodIsShow){  
    		commentView.setDefaultHint();
    		commentView.setCommentParams(this, targetType, targetValue);
    		commentView.hideInputMethod();
    		return true;
 	    }  
    	return false;
    }
	
	
	private void addListener() {
		butBack.setOnClickListener(this);
		xListView.setPullLoadEnable(true);
		xListView.hideLoadMore();
		xListView.setXListViewListener(this);
		xListView.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if( inputMethodIsShow ){
					commentView.setDefaultHint();
		    		commentView.setCommentParams(bActivity, targetType, targetValue);
		    		commentView.hideInputMethod();
					return ;
				}
				
				CommentBean info = (CommentBean) parent.getAdapter().getItem(position);
				if(Const.phone_number.equals(info.getCommentUserAccount())){
					commentView.setDefaultHint();
					commentView.setCommentParams(bActivity, targetType, targetValue);
				}else{
					commentView.setHintString(info.commentUserNickName);
					commentView.setReplyParams(bActivity, targetType, targetValue, info.commentUserId, info.commentUserAccount, info.commentId);
				}
				commentView.showInputMethod();
			}
		});
		
		commentView.setCommentParams(bActivity, targetType, targetValue);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				commentView.hideInputMethod();
				setReturnResult( );
				finish();
				break;
		}
		
	}
	
	@Override
	public void onBackPressed() {
		setReturnResult( );
		super.onBackPressed();
	}
	
	private void setReturnResult( ){
			setResult(this.RESULT_OK);
	}
	
	public void setData(Message msg) {
		if (msg == null) return;
		final int flag = Integer.valueOf(msg.obj.toString());
		if(2==flag  && (resultInfo == null || resultInfo.isEmpty() || resultInfo.size() < pageNumber)){
			//TODO
			xListView.setReadyHint("没有更多数据了");
		}
		if(null!=resultInfo && !resultInfo.isEmpty()){
			if (commentList != null && flag != 2) commentList.clear();
			
			commentList.addAll(resultInfo);
			resultInfo.clear();
		}
		
		if(null==commentList || commentList.isEmpty() || commentList.size()==0){
			loadingView.changeLoadingStatus(1);
			commentView.showInputMethod();
		}else{
			if(0==flag || -1==flag){
				xListView.setAdapter(commentListAdapter);
				loadingView.setVisibility(View.GONE);
//				contentView.setVisibility(View.VISIBLE);
				xListView.setVisibility(View.VISIBLE);
			}
			commentListAdapter.notifyDataSetChanged();
		}
		xListView.stopRefresh();
		xListView.stopLoadMore();
		xListView.hideLoadMore();
	}
	
	private class getCommentListActionListener
	        implements
	        ActionListener
	{
		private int flag; //0 为首次加载、1为下拉刷新    2为上拉加载更多    
		                  
		private getCommentListActionListener(int flag) {
			this.flag = flag;
		}
		
		@SuppressWarnings ("unchecked")
        @Override
		public void OK(Object obj) {
			resultInfo = (List<CommentBean>) obj;
			
			Message msg = new Message();
			msg.what = DefaultConsts.COMMENT_LIST_UPDATEUI;
			msg.obj = flag;
			handler.sendMessage(msg);
		}
		
		@Override
		public void ERROR(int resultCode, final String message) {
			handler.post(new Runnable()
			{
				@Override
				public void run() {
					Util.showToast(context, message);
					if(0L == currentCommentTime) loadingView.changeLoadingStatus(-1);
				}
			});
		}
		
		@Override
		public void HTTPERROR(int statusCode) {
			handler.post(new Runnable()
			{
				@Override
				public void run() {
					if(0L == currentCommentTime) loadingView.changeLoadingStatus(-1);
				}
			});
		}
	}
	
	private class CommentListAdapter
	        extends
	        BaseAdapter
	{
		@Override
		public int getCount() {
			return (commentList == null ? 0 : commentList.size());
		}
		
		@Override
		public Object getItem(int position) {
			return (commentList == null ? null : commentList.get(position));
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			CommentListHolder commentListHolder = new CommentListHolder();
			if (convertView == null)
			{
				convertView = LayoutInflater.from(context).inflate(R.layout.comment_list_item, null);
				commentListHolder.ivHeadImg = (CircleImageView) convertView.findViewById(R.id.comment_list_item_head_img);
				commentListHolder.tvName = (TextView) convertView.findViewById(R.id.comment_list_item_name_tv);
				commentListHolder.tvTime = (TextView) convertView.findViewById(R.id.comment_list_item_time_tv);
				commentListHolder.tvContext = (TextView) convertView.findViewById(R.id.comment_list_item_context_tv);
				convertView.setTag(commentListHolder);
			}
			else
			{
				commentListHolder = (CommentListHolder) convertView.getTag();
			}
			
			CommentBean commentBean = (CommentBean) getItem(position);
			commentListHolder.tvName.setText(getNickName(commentBean));
			commentListHolder.tvTime.setText(DateUtil.getRegionTime(commentBean.createTime));
			commentListHolder.tvContext.setText(getContent(commentBean));
			
			if (Util.isNotEmpty(commentBean.commentUserHeadImage))
			{
				ImageLoaderUtil.loadWebUrl(commentBean.commentUserHeadImage, commentListHolder.ivHeadImg);
			}
			else
			{//如果URL为空 则显示默认头像
				commentListHolder.ivHeadImg.setImageResource(R.drawable.comment_list_default_head_img);
			}
			
			return convertView;
		}
	}
	private String getNickName(CommentBean bean){
		if(null==bean) return "";
		if(Util.isNotEmpty(bean.commentUserNickName)) return bean.commentUserNickName;
		final String account = bean.commentUserAccount;
		if(Util.isEmpty(account)) return "";
		return Util.formatPhone(account);
	}
	private String getContent(CommentBean bean){
		if(null!=bean){
			return Util.isEmpty(bean.replyCommentUserNickName)?bean.content:String.format("回复%s: %s", bean.replyCommentUserNickName,bean.content);
		}
		return "";
	}
	
	private class CommentListHolder
	{
		TextView        tvName, tvContext, tvTime;
		CircleImageView ivHeadImg;
	}
	
	@Override
	public void onRefresh() {
		xListView.setReadyHint("");
		xListView.setPullLoadEnable(true);
		getData(1);
	}
	
	@Override
	public void onLoadMore() {
		getData(2);
	}
	
	/**
	 * @param flag 0 为首次加载、1为下拉刷新    2为上拉加载更多    -1为评论成功后刷新
	 * 
	 */
	public void getData(int flag){
		if (NetworkUtil.isNetAvailable(context))
		{
			if(flag==2){
				currentCommentTime = commentList.get(commentList.size()-1).getCreateTime();
			}else{
				currentCommentTime = 0L;
				refrushTime = System.currentTimeMillis();
				xListView.setRefreshTime(DateUtil.getRegionTime(refrushTime));
			}
			new QryCommentListAction(context, targetType, targetValue, flag==-1?0L:currentCommentTime, flag==-1?commentList.size()+1:pageNumber, new getCommentListActionListener(flag)).start();
		}
		else
		{
			if(flag==0){
				new NoNetDialog(context).show();
			}else{
				Util.showToast(bActivity, "请检查网络");
				xListView.stopRefresh();
				xListView.stopLoadMore();
			}
		}
	}
}
